package cn.wit.front.service.impl;

import cn.wit.front.condition.LoginCondition;
import cn.wit.front.condition.UserRegisterCondition;
import cn.wit.front.mapper.UserMapper;
import cn.wit.front.service.LoginService;
import cn.wit.front.utils.AesUtils;
import cn.wit.front.vo.LoginVO;
import cn.wit.utils.pojo.User;
import cn.wit.utils.response.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result login(LoginCondition condition) {
        log.info(condition.toString());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", condition.getUsername());
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            return Result.error("登录失败");
        }
        String decrypt = null;
        try {
            decrypt = AesUtils.decrypt(user.getPassword(), user.getPwKey());
            System.out.println(decrypt);
        } catch (Exception e) {
            return Result.error("登录失败");
        }
        if (condition.getPassword().equals(decrypt)) {
            String token = user.getId().toString() + UUID.randomUUID().toString() + user.getId();
            redisTemplate.opsForValue().set(token, user);
            LoginVO loginVO = new LoginVO();
            loginVO.setToken(token);
            loginVO.setUsername(condition.getUsername());
            loginVO.setUserId(user.getId());
            return Result.ok(loginVO);
        }
        return Result.error("登录失败");
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete(token);
        return Result.ok();
    }
    @Override
    public Result register(UserRegisterCondition condition) {
        String password = null;
        try {
            password = AesUtils.encrypt(condition.getPassword(), "witcswitcswitcsw");
        } catch (Exception e) {
            return Result.error("注册失败");
        }
        User user = User.builder()
                .username(condition.getUsername())
                .password(password)
                .name(condition.getName())
                .studentClass(condition.getStudent_class())
                .companyJobName(condition.getCompany_job_name())
                .pwKey("witcswitcswitcsw")
                .build();
        int insert = userMapper.insert(user);
        if(insert > 0) {
            return Result.ok();
        }
        return Result.error("注册失败");
    }
}
